﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;

namespace Niknak.Services.ServiceCore.Msmq
{
    public class Helper<ConfigurationSettings, ExceptionHandler> 
        where ConfigurationSettings : IMsmqConfig, new()
        where ExceptionHandler : IExceptionHandler, new()
    {
        public static ConfigurationSettings Settings
        {
            get { return new ConfigurationSettings(); }
        }

        public static ExceptionHandler CustomExceptionHandler
        {
            get { return new ExceptionHandler(); }
        }

        private static MessageQueue _QueueWriter = null;
        public static MessageQueue QueueWriter
        {
            get
            {
                if (_QueueWriter == null)
                {
                    _QueueWriter = new MessageQueue(Settings.MsmqWriteAddress, QueueAccessMode.Send);
                    _QueueWriter.Formatter = new BinaryMessageFormatter();
                }

                return _QueueWriter;
            }
        }

        private static MessageQueue _QueueReader = null;
        public static MessageQueue QueueReader
        {
            get
            {
                if (_QueueReader == null)
                {
                    _QueueReader = new MessageQueue(Settings.MsmqReadAddress, QueueAccessMode.ReceiveAndAdmin);
                    _QueueReader.Formatter = new BinaryMessageFormatter();
                    
                    //MessagePropertyFilter propertyFilter = new MessagePropertyFilter()
                    //{
                    //    Priority = true
                    //};
                    //_QueueReader.MessageReadPropertyFilter = propertyFilter;
                }

                return _QueueReader;
            }
        }

        public static bool Send(Enums.Msmq.MessageType messageType, MessagePriority priority, object body)
        {
            Message message = new Message();
            message.Formatter = new BinaryMessageFormatter();
            message.Label = messageType.ToString();
            message.Body = body;
            message.Priority = priority;

            try
            {
                QueueWriter.Send(message);
                return true;
            }
            catch (Exception ex)
            {
                CustomExceptionHandler.ExceptionLogEntry(ex);
            }

            return false;
        }
    }
}
